package com.cjm.algorithm.leetcode.listnode.first;

import com.cjm.algorithm.ListNode;

public class Ti160Easy {
    public static void main(String[] args) {

    }

    /**
     * 2023-09-13 22:29:05
     *
     * @param headA
     * @param headB
     * @return
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        //return m1(headA, headB);
        if (headA == null || headB == null) {
            return null;
        }
        int numA = 0, numB = 0;
        ListNode tA = headA, tB = headB;
        while (tA != null) {
            numA++;
            tA = tA.next;
        }
        while (tB != null) {
            numB++;
            tB = tB.next;
        }
        int before = Math.abs(numA - numB);
        while (before > 0) {
            if (numA > numB) {
                headA = headA.next;
            } else {
                headB = headB.next;
            }
            before--;
        }
        while (headA != null && headB != null) {
            if (headA.equals(headB)) {
                return headA;
            } else {
                headA = headA.next;
                headB = headB.next;
            }
        }
        return null;
    }

    /**
     * 都各自走一遍
     *
     * @param headA
     * @param headB
     * @return
     */
    private static ListNode m1(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode pA = headA, pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }
}
